package org.axed.user.client;

import com.google.gwt.user.client.Window;
import java.util.ArrayList;
import java.util.Iterator;
import org.axed.user.client.util.IntList;

/**
 * A Collection of listeners that forwards fire events to all of its contents.
 */
public class AxedListenerCollection {
	/**
	 * The listeners
	 */
	ArrayList listeners = new ArrayList();

	/**
	 * Their priority
	 */
	IntList prios = new IntList();

	/**
	 * Adds a listener.
	 */
	public void addListener(AxedListener listener, int priority) {
		int p;
		for(p = 0; p < prios.size(); p++) {
			if (prios.get(p) > priority) {
				break;
			}
		}
		listeners.add(p, listener);
		prios.add(p, priority);
	}

	public void clear() {
		listeners.clear();
		prios.clear();
	}

	/**
	 * Fires an event to all members of this collection.
	 *
	 * @param event    the event send.
	 */
	public void fireEvent(AxedEvent event) {
		event.cancel = false;
   		for (Iterator it = listeners.iterator(); it.hasNext();) {
      		((AxedListener) it.next()).onAxedEvent(event);
			if (event.cancel) {
				break;
			}
		}
	}

	public void remove(AxedListener o) {
		prios.remove(listeners.indexOf(o));
		listeners.remove(o);
	}
}
